<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2020/5/23 0023
 * Time: 16:21
 */

namespace Api\Controller;

/**
 * Class UserMessageController
 * @package Api\Controller
 */
class UserMessageController extends BaseController
{
    protected $mid;
    protected $member;
    protected $table = 'ShopFansMessage';
    public function __construct()
    {
        parent::__construct();
        //验证用户
        $openid = I('request.openid','');
        empty($openid) && $this->error('openid缺失！');
        $member = M('Usermember')->where(['openid' => $openid])->find();
        empty($member) && $this->error('用户不存在！');
        $this->mid = $member['id'];
        $this->member = $member;
    }
    /**
     * 消息列表 根据发送用户分组 限定GET请求
     * 默认10条分页
     */
    public function index()
    {
        if(!IS_GET){
            $this->error('请求错误！');
        }
        $page = I('get.page',1);
        $limit = I('get.limit',10);
        if(!is_numeric($page)){
            $page = 1;
        }
        if(!is_numeric($limit) || $limit < 10){
            $limit = 10;
        }

        $start = ($page-1)*$limit;
        //按照单个用户分组查询
        $where = "select * from
                 (select * from onethink_shop_fans_message where
                     (sid={$this->mid} and sender_deleted <> 1) 
                     or
                     (mid={$this->mid} and receiver_deleted <> 1)
                     order by create_at desc limit 999999) a 
                 group by concat(least(sid,mid),'-',greatest(sid,mid))
                 limit {$start},{$limit}";
        $list = M()->query($where);
        // 查询用户信息
        $mids = array_unique(array_column($list,'mid'));
        $member = M('Usermember')->where(['id' => array('in',$mids)])->field('id,username,head_icon')->select();
        // 数据列表处理
        foreach ($list as &$item) {
            if($item['type'] === '2'){
                $item['content'] = thumb_path($item['content']);
            }
            $item['member'] = [];
            foreach ($member as $value) if($item['mid'] === $value['id']) {
                $item['member'] = $value;
            }
        }
        $this->success('获取消息列表成功！',$list);
    }

    /**
     * 发送消息 可发图片 文字 需选择接收人 限定post请求
     */
    public function save()
    {
        if(!IS_POST){
            $this->error('请求错误！');
        }
        $sid = I('sid'); // 接收人用户ID
        empty($sid) && $this->error('请选择消息接收人！');
        $type = I('type'); // 消息类型 1文字 2 图片
        if(!in_array($type,['1','2'])){
            $this->error('消息类型错误！');
        }
        $content = I('content');// 消息内容 类型为图片时只可为数字
        empty($content) && $this->error('消息内容不能为空！');
        if($type == '2' && !is_numeric($content)){
            $this->error('消息内容和消息类型不匹配！');
        }
        $res = M($this->table)->add([
            'sid' => $sid,
            'mid' => $this->mid,
            'type' => $type,
            'content' => $content
        ]);
        if($res){
            $this->success('消息发送成功！');
        } else {
            $this->error('消息放送失败！');
        }
    }

    /**
     * 消息详情
     * @param $id int 用户id
     */
    public function read($id)
    {
        $member = M('Usermember')->where(['id' => $id])->find();
        empty($member) && $this->error('用户不存在！','');
        $where = "select id,sid,mid,type,content,create_at from onethink_shop_fans_message where(((sid={$this->mid}) and (mid={$id}) and(sender_deleted=0)) or ((sid={$id}) and (mid={$this->mid}) and(receiver_deleted=0))) order by create_at desc";
        $list = M()->query($where);
        // 数据列表处理
        foreach ($list as &$item) {
            if($item['sid'] == $this->mid){
                $item['modal'] = 'self';
            } else {
                $item['modal'] = 'other';
            }
            if($item['type'] === '2'){
                $item['content'] = thumb_path($item['content']);
            }
        }
        $response = [
            'self' => $this->member,
            'other' => $member,
            'message' => $list
        ];
        $this->success('获取消息成功！',$response);
    }

    /**
     * 删除某一条消息
     * 不一定必须用delete请求 路由随便写 能达到目的就行
     * @param $id int 消息ID
     */
    public function delete($id)
    {
        if(!IS_DELETE){
            $this->error('请求错误！');
        }
        $where = ['id' => $id];
        $message = M($this->table)->where($where)->find();
        empty($message) && $this->error('消息不存在！');
        if($message['sid'] !== $this->mid && $message['mid'] !== $this->mid){
            $this->error('没有权限！');
        }
        if($message['sid'] === $this->mid){
            $data = ['sender_deleted' => '1'];
        } else {
            $data = ['receiver_deleted' => '1'];
        }
        $res = M($this->table)->where($where)->save($data);
        if($res !== false){
            $this->success('消息删除成功！');
        } else {
            $this->error('消息删除失败！');
        }

    }

    /**
     * 删除跟某个人的所有聊天记录
     * @param $id int 用户ID
     */
    public function deleteList($id)
    {
        if(!IS_DELETE){
            $this->error('请求错误！');
        }
        $member = M('Usermember')->where(['id' => $id])->find();
        empty($member) && $this->error('用户不存在！');

        $where1['sid']  = array('eq', $this->mid);
        $where1['mid']  = array('eq',$id);

        $where2['sid']  = array('eq',$id);
        $where2['mid']  = array('eq', $this->mid);
        M()->startTrans();// 开启事务
        $res1 = M($this->table)->where($where1)->save(['sender_deleted' => '1']);
        $res2 = M($this->table)->where($where2)->save(['receiver_deleted' => '1']);
        if($res1 !== false && $res2 !== false){
            M()->commit();
            $this->success('删除成功！');
        } else {
            M()->rollback();
            $this->error('删除失败！');
        }
    }
    /**
     * 删除所有消息
     */
    public function deleteAll()
    {
        if(!IS_DELETE){
            $this->error('请求错误！');
        }
        $where1['sid']  = $this->mid;

        $where2['mid']  = $this->mid;

        M()->startTrans();// 开启事务
        $res1 = M($this->table)->where($where1)->save(['sender_deleted' => '1']);
        $res2 = M($this->table)->where($where2)->save(['receiver_deleted' => '1']);
        if($res1 !== false && $res2 !== false){
            M()->commit();
            $this->success('删除成功！');
        } else {
            M()->rollback();
            $this->error('删除失败！');
        }
    }
}